package org.example.struct.array2;

import com.alibaba.fastjson2.JSON;

/**
 * @author liyishan
 * @date 2023/8/29 09:23
 * @apiNote
 */

public class Test00031NextPermutation {
    public static void main(String[] args) {
        int[] nums = new int[]{2,3,1};
        test(nums);
        System.out.println(JSON.toJSON(nums));
    }

    public static void test(int[] nums) {
        int n = nums.length;
        int left = -1;
        int right = 0;
        for(int i = n-1;i>0;i--){
            if(nums[i]>nums[i-1]){
                left = i-1;
                break;
            }
        }
        if(left >= 0){
            for(int i = n-1;i>left;i--){
                if(nums[i]>nums[left]){
                    right = i;
                    break;
                }
            }
            swap(nums,left,right);
        }
        reverse(nums,left+1);

    }

    public static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void reverse(int[] nums, int start) {
        int left = start, right = nums.length - 1;
        while (left < right) {
            swap(nums, left, right);
            left++;
            right--;
        }
    }
}
